import mongoose from 'mongoose'

const sysUsersSchema = new mongoose.Schema({
  userNick: { type: String, default: '' },
  userAccount: { type: String, default: '' },
  userPassword: { type: String, default: '' },
  userName: { type: String, default: '' },
  userRoles: [String],
  userAvatar: { type: String, default: '' },
  activeFlag: { type: Number, default: 0 },
  deleteFlag: { type: Number, default: 0 },
  createTime: { type: Date, default: Date.now },
  updateTime: { type: Date, default: Date.now },
  loginTime: { type: Date, default: Date.now }
})

// 每次执行都会调用,时间更新操作
sysUsersSchema.pre('save', function(next) {
  if (this.isNew) {
    this.createTime = this.updateTime = Date.now()
  } else {
    this.updateTime = Date.now()
  }
  next()
})

// 查询的静态方法
sysUsersSchema.statics = {
  fetch: function(cb) { // 查询所有数据
    return this
      .find()
      .sort('updateTime') // 排序
      .exec(cb) // 回调
  },
  findById: function(id, cb) { // 根据id查询单条数据
    return this
      .findOne({ _id: id })
      .exec(cb)
  }
}

export default sysUsersSchema
